package util;

import java.io.*;
import java.net.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.xml.sax.InputSource;

import classifier.WekaClassifier;

public class Service {
	private int port;
	private int i;

	public Service(int port) {
		this.i = 1;
		this.port = port;

	}

	public void start() {
		ServerSocket server = null;
		Socket client = null;
		try {
			server = new ServerSocket(port);
			System.out.println("Web Server is listening on port "
					+ server.getLocalPort());
			for (;;) {
				client = server.accept();
				new ConnectionThread(client, i).start();
				i++;
			}
		} catch (Exception e) {
			System.out.println(e);
		}
	}

}

class ConnectionThread extends Thread {
	Socket client;

	int counter;

	public ConnectionThread(Socket cl, int c) {
		client = cl;
		counter = c;
	}

	public void run() {
		try {
			// get the classifier
			WekaClassifier wc = null;
			try {
				FileInputStream fileIn = new FileInputStream("nbc.ser");
				ObjectInputStream in = new ObjectInputStream(fileIn);
				wc = (WekaClassifier) in.readObject();
				in.close();
				fileIn.close();
			} catch (IOException i) {
				i.printStackTrace();
				return;
			} catch (ClassNotFoundException c) {
				System.out.println("WekaClassifier class not found");
				c.printStackTrace();
				return;
			}

			String destIP = client.getInetAddress().toString();
			int destport = client.getPort();
			System.out.println("Connection " + counter + ":connected to "
					+ destIP + " on port " + destport + ".");
			PrintStream outstream = new PrintStream(client.getOutputStream());
			// System.out.println("try to get input");

			DataInputStream instream = new DataInputStream(
					client.getInputStream());

			// System.out.println("try to get inline");

			String inline = instream.readLine(); // read request
			System.out.println("Received:" + inline);
			// if (this.postrequest(inline)) {
			// System.out.println("inline");
			// }

			// System.out.println("try to analyze");

			if (getrequest(inline)) { // if it is a GET
				String input = getfilename(inline);

				// System.out.println("try to compute");
				String[] query= input.split("%#%&%");
				String result= "";

				for(int i=0;i<query.length;i++){
				result+= wc.classify(query[i])+",";
				
				DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
				Date date = new Date();
				System.out.println(dateFormat.format(date));				
				System.out.println("PROCESSED " + query[i] + " requested.");
				}
				// System.out.println("complete compute");
				
				result=result.substring(0, result.length());
				String out="CLASSFIER OK ####";
				
//				outstream.println("CLASSFIER OK");
//				outstream.println("####");
				
//				if (result.equals("4")) {
//					out+="POSITIVE";
//				//	sendMain(outstream, "POSITIVE");
//				}
//				if (result.equals("0")) {
//					out+="NEGATIVE";
//
//				//	sendMain(outstream, "NEGATIVE");
//				}
//				if ((!result.equals("0")) && (!result.equals("4") )) {
//					out+="NETURAL";
//
//				//	sendMain(outstream, "NEGATIVE");
//				}
				
				out+=result;
				
				out+=("####");
			//	outstream.println("\r\n");
				

				sendMain(outstream, out);

				outstream.flush();
			//	outstream.flush();

			}
			long m1 = 1;
			while (m1 < 111) {
				m1++;
			}

			client.close();
		} catch (IOException e) {
			System.out.println("Exception:" + e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/* 获取请求类型是否为“GET” */
	boolean getrequest(String s) {
		if (s.length() > 0) {
			if (s.indexOf("GETCLASSIFY") == 0)
				return true;
		}
		return false;
	}

	boolean postrequest(String s) {
		if (s.length() > 0) {
			if (s.substring(0, 3).equalsIgnoreCase("POST"))
				return true;
		}
		return false;
	}

	String getfilename(String s) {
		String f = s.substring(s.indexOf(32) + 1);

		try {
			int begin = f.indexOf("#@#");
			int end = f.indexOf("#@#", begin + 2);
			f = f.substring(begin + 3, end);
		} catch (StringIndexOutOfBoundsException e) {
			System.out.println("Exception:" + e);
		}

		return f;
	}

	boolean pass(String filename) {
		return false;
	}

	void sendfile(PrintStream outs, File file) {
		try {
			DataInputStream in = new DataInputStream(new FileInputStream(file));
			int len = (int) file.length();
			byte buf[] = new byte[len];
			in.readFully(buf);
			outs.write(buf, 0, len);
			outs.flush();
			in.close();
		} catch (Exception e) {
			System.out.println("Error retrieving file.");
			System.exit(1);
		}
	}

	void sendMain(PrintStream outs, String output) {
		try {
			// DataInputStream in = new DataInputStream(new
			// FileInputStream(file));

			// String output=Util.genHTML();
			InputStream is = new ByteArrayInputStream(output.getBytes());
			DataInputStream tmp = new DataInputStream(is);

			int len = output.length();

			byte buf[] = new byte[len];
			tmp.readFully(buf);
			outs.write(buf, 0, len);
			outs.flush();
			tmp.close();
		} catch (Exception e) {
			System.out.println("Error retrieving file.");
			System.exit(1);
		}
	}
}
